import time
from django.utils.deprecation import MiddlewareMixin


class RequestTimingMiddleware(MiddlewareMixin):
    """统计请求耗时中间件"""

    def process_request(self, request):
        request.start_time = time.time()

    def process_response(self, request, response):
        if hasattr(request, 'start_time'):
            duration = time.time() - request.start_time
            # 记录到响应头
            response['X-Request-Duration'] = f"{duration:.3f}s"
            # 也可以记录到日志
            print(f"Request to {request.path} took {duration:.3f} seconds")
        return response